package com.ty.service;

import cn.hutool.core.date.DateUnit;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.NumberUtil;
import cn.smart.core.exception.BizException;
import com.ty.dao.PoItemDao;
import com.ty.dao.PoMasterDao;
import com.ty.entity.PoItem;
import com.ty.entity.PoItemQuery;
import com.ty.entity.PoMaster;
import com.ty.entity.PoMasterQuery;
import com.ty.enums.PoStatus;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.List;


@Service
public class PoMasterService {

    @Autowired
    private PoMasterDao poMasterDao;
    @Autowired
    private PoItemDao poItemDao;

    public List<PoMaster> select(PoMasterQuery query) {
        return poMasterDao.select(query);
    }

    @Transactional  
    public Integer insert(PoMaster poMaster) {
        String poId = "PO"+ DateUtil.format(DateUtil.date(),"yyyyMMddHHmmssSSS");
        poMaster.setStatus(PoStatus.NEW.getCode());
        BigDecimal totalPrice = BigDecimal.ZERO;
        List<PoItem> items = poMaster.getItems();
        for (PoItem item:items){
            item.setPoId(poId);
            BigDecimal add = NumberUtil.add(totalPrice,NumberUtil.mul(item.getPrice(),item.getQty()));
        }
        if (totalPrice.doubleValue()!= poMaster.getTotalPrice().doubleValue()){
            throw new BizException(407,"价格不一致");
        }

        // to do
        if (totalPrice.doubleValue()<=2000){
            poMaster.setStatus(PoStatus.DISTRIBUTION.getCode());
        }else {
            //待审核  发送钉钉通知
        }

         poMasterDao.insert(poMaster);
        poItemDao.insertBatch(poMaster.getItems());
        return 0;
    }

    public Integer update(PoMaster poMaster) {
        return poMasterDao.update(poMaster);
    }

    public Integer delete(Integer id) {
        return poMasterDao.delete(id);
    }

    public int approve(String id) {
        return poMasterDao.updateStatus(id,PoStatus.APPROVE.getCode());
    }

    public int reject(String id) {
        return poMasterDao.updateStatus(id,PoStatus.REJECT.getCode());
    }

    public int interrupt(String id) {
        return poMasterDao.updateStatus(id,PoStatus.CANCEL.getCode());
    }
}